#include "parse.h"
#include "exp.h"

static expressionADT ReadF(scannerADT scanner);

expressionADT ParseExp(scannerADT scanner)
{
    expressionADT exp;

    exp = ReadE(scanner);
    if (MoreTokensExist(scanner)) {
        Error("ParseExp: %s unexpected", ReadToken(scanner));
    }
    return (exp);
}

expressionADT ReadE(scannerADT scanner)
{
	expressionADT exp, rhs;
    string token;

	exp = ReadT(scanner);
	if(!MoreTokensExist(scanner))
		return (exp);
	token = ReadToken(scanner);
	if (StringEqual(token, "+") || StringEqual(token, "-"))
	{
		rhs = ReadE(scanner);
		exp = NewCompoundExp(token[0], exp, rhs);
	}
	else SaveToken(scanner, token); 
	return (exp);
}

static expressionADT ReadF(scannerADT scanner)
{
    expressionADT exp;
    string token;

    token = ReadToken(scanner);
    if (StringEqual(token, "(")) {
        exp = ReadE(scanner);
        if (!StringEqual(ReadToken(scanner), ")")) {
            Error("Unbalanced parentheses");
        }
    } else if (isdigit(token[0])) {
        exp = NewIntegerExp(StringToInteger(token));
    } else if (isalpha(token[0])) {
        exp = NewIdentifierExp(token);
    } else {
        Error("Illegal term in expression");
    }
    return (exp);
}

expressionADT ReadT(scannerADT scanner)
{
	expressionADT exp, rhs;
    string token;

	exp = ReadF(scanner);
	if(!MoreTokensExist(scanner))
		return (exp);
	token = ReadToken(scanner);
	if (StringEqual(token, "*") || StringEqual(token, "/"))
	{
		rhs = ReadT(scanner);
		exp = NewCompoundExp(token[0], exp, rhs);
	}
	else SaveToken(scanner, token); 
	return (exp);
}

int testIfInteger(scannerADT scanner)
{
	string s;
	int len, i;

	s = ReadToken(scanner);
	
	len = StringLength(s);
	for (i = 0; i<len; i++)
	{
		if(!isdigit(s[i]))
		{
			return -1;
		}
	}
	return (StringToInteger(s));
}